package com.bjpowernode.controllers;

import com.bjpowernode.entities.TCustomer;
import com.bjpowernode.querys.CustomerQuery;
import com.bjpowernode.result.Result;
import com.bjpowernode.services.CustomerService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

@RestController
public class CustomerController {
    @Resource
    private CustomerService customerService;

    @GetMapping(value = "/api/customer/{id}")
    public Result getCustomerById(@PathVariable(value = "id") Integer id) {
        TCustomer tCustomer = customerService.getCustomerById(id);
        return Result.OK(tCustomer);
    }

    @GetMapping(value = "/api/customers")
    public Result getCustomersByPage(@RequestParam(value = "current") Integer current) {
        PageInfo<TCustomer> pageInfo = customerService.getCustomersByPage(current);
        return Result.OK(pageInfo);
    }

    @PostMapping(value = "/api/customer")
    public Result addCustomer(@RequestBody CustomerQuery customerQuery) {
        boolean convert = customerService.convertCustomer(customerQuery);
        return convert ? Result.OK() : Result.FAIL();
    }

    @GetMapping(value = "/api/exportExcel")
    public void exportExcel(HttpServletResponse response, @RequestParam(value = "ids") String ids) throws IOException {
        List<String> idList = null;
        if (StringUtils.hasText(ids))
            idList = Arrays.asList(ids.split(","));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); //Excel
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + System.currentTimeMillis() + ".xlsx");
        OutputStream outputStream = response.getOutputStream(); //response的输出流（响应流）
        customerService.exportExcel(outputStream, idList);
    }
}
